﻿using fuzhu;
using Newtonsoft.Json;
using SqlSugar;
using System.Data;
using System.Text;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.GL;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class GLaccvouchVM : Api_GlModel
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        //public string cDatabase = "";
        //本币
        public string benbi { get; set; }
        /// <summary>
        /// 获取凭证序号
        /// </summary>
        /// <param name="csign">凭证类别</param>
        /// <returns></returns>
        public int getSignSeq(string csign)
        {
            string sql = @" select isignseq    from   dsign   where csign = '" + csign + "' ";
            object obj = DbHelper2.ExecuteScalar(sql, conStr);
            if (obj != null)
            {
                return DbHelper.GetDbInt(obj);
            }
            else
            {
                return -1;
            }
        }
        /// <summary>
        /// 凭证类别字是否合法
        /// </summary>
        /// <param name="csign"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static bool illg_dsign(string csign, ref string errMsg, string conStr)
        {
            string f1 = " select count(1) " +
                           " from   dsign " +
                           " where csign = '" + csign + "' ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));

            if (icount == 0)
            {
                errMsg = "不存在凭证类别字:" + csign;
                return false;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 判断会计期间是否结账
        /// </summary>
        /// <param name="iyear"></param>
        /// <param name="imonth"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool CheckJieZhang(int iyear, int imonth, ref string errMsg)
        {
            string f1 = " select count(1) " +
                        " from    gl_mend " +
                        " where iyear = '" + iyear.ToString() + "' and iperiod = '" + imonth.ToString() + "' ";

            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));

            if (icount == 0)
            {
                errMsg += "账套不存在会计期间:" + iyear.ToString() + "年" + imonth.ToString() + "月!";
                return false;
            }
            else
            {
                f1 = " select convert(int,convert(bit,isnull(bflag,0))) 总账结账标志 " +
                     " from     gl_mend " +
                     " where iyear = '" + iyear.ToString() + "' and iperiod = '" + imonth.ToString() + "' ";
                int bflag = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
                if (bflag == 0)
                {
                    return true;
                }
                else
                {
                    errMsg += "账套会计期间:" + iyear.ToString() + "年" + imonth.ToString() + "月已结账,不能导入!";
                    return false;
                }
            }
        }

        /// <summary>
        /// 获得凭证编号
        /// </summary>
        /// <param name="iyear"></param>
        /// <param name="iperiod"></param>
        /// <param name="csign">凭证类别字</param>
        /// <returns></returns>
        public string get_ino_id(int iyear, int iperiod, string csign)
        {
            string f1 = " select count(1) " +
                          " from     GL_accvouch " +
                          " where iyear = '" + iyear.ToString() + "' and iperiod = '" + iperiod.ToString() + "' and csign='" + csign + "' ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount == 0)
            {
                return "1";
            }
            else
            {
                f1 = " select max(ino_id)+1 " +
                        " from     GL_accvouch " +
                        " where iyear = '" + iyear + "' and iperiod = '" + iperiod + "' and csign='" + csign + "' ";
                int new_ino_id = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
                return new_ino_id.ToString();
            }
        }
        /// <summary>
        /// 获得coutno_id
        /// </summary>
        /// <returns></returns>
        public string get_coutno_id()
        {
            //string f1 = " select 'GL'+RIGHT('0000000000000'+CAST(isnull(max(right(coutno_id,len(coutno_id)-2)),0)+1 AS nvarchar(50)),13) coutno_id  from GL_accvouch  where coutno_id  like 'GL%'";
            //DataSet ds = modelhelper.SqlHelper.ExecuteDataSet(f1);
            string coutno = DbHelper.GetDbString(DbHelper2.ExecuteScalar(@"declare @p4 nvarchar(17)
exec   Ap_Proc_CancelNo N'PZ', N'GL', default, @p4 output
select @p4",conStr));
            return coutno;
            //if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            //{
            //    return a;
            //}
            //else
            //{
            //    return null;
            //}
        }


        /// <summary>
        /// 判断科目是否辅助核算
        /// <param name="code">科目</param>
        /// <param name="iyear">年</param>
        /// <param name="dep_fzhs">是否部门辅助</param>
        /// <param name="person_fzhs">是否人员辅助</param>
        /// <param name="cus_fzhs">是否客户辅助</param>
        /// <param name="vendor_fzhs">是否供应商辅助</param>
        /// <param name="fitem_fzhs">是否项目核算</param>
        /// <param name="citem_class">项目大类编码</param>
        /// <param name="bend">是否末级科目</param>
        /// <param name="bclose">是否封存</param>
        ///  <param name="bclose">受控系统</param>
        /// ...
        public bool getFuZhuHeSuan(string code, int iyear, ref int dep_fzhs, ref int person_fzhs,
                                ref int cus_fzhs, ref int vendor_fzhs, ref int fitem_fzhs, ref string cass_item,
                                ref string cexch_name, ref int bend, ref int bclose,
                                ref int bcDefine1, ref int bcDefine2, ref int bcDefine3, ref int bcDefine4,
                                ref int bcDefine5, ref int bcDefine6, ref int bcDefine7, ref int bcDefine8,
                                ref int bcDefine9, ref int bcDefine10, ref int bcDefine11, ref int bcDefine12,
                                ref int bcDefine13, ref int bcDefine14, ref int bcDefine15, ref int bcDefine16,
                                ref string cother,
                                ref string errMsg)
        {
            try
            {
                string sql = " select ccode,ccode_name, " +
                            "        convert(int, convert(bit, bdept)) 部门核算, " +
                            "		convert(int, convert(bit, bperson)) 人员核算, " +
                            "        convert(int, convert(bit, bcus)) 客户核算, " +
                            "        convert(int, convert(bit, bsup)) 供应商核算, " +
                            "        convert(int, convert(bit, bitem)) 项目核算, " +
                            "        isnull(cass_item,'') 项目大类编码," +
                            "        isnull(cexch_name,'')  币种," +
                            "        convert(int, convert(bit, bend)) 末级科目, " +
                            "        convert(int, convert(bit, bclose)) 科目封存, " +
                            "        convert(int, convert(bit, bcDefine1)) 是否有自定义项1, " +
                            "        convert(int, convert(bit, bcDefine2)) 是否有自定义项2, " +
                            "        convert(int, convert(bit, bcDefine3)) 是否有自定义项3, " +
                            "        convert(int, convert(bit, bcDefine4)) 是否有自定义项4, " +
                            "        convert(int, convert(bit, bcDefine5)) 是否有自定义项5, " +
                            "        convert(int, convert(bit, bcDefine6)) 是否有自定义项6, " +
                            "        convert(int, convert(bit, bcDefine7)) 是否有自定义项7, " +
                            "        convert(int, convert(bit, bcDefine8)) 是否有自定义项8, " +
                            "        convert(int, convert(bit, bcDefine9)) 是否有自定义项9, " +
                            "        convert(int, convert(bit, bcDefine10)) 是否有自定义项10, " +
                            "        convert(int, convert(bit, bcDefine11)) 是否有自定义项11, " +
                            "        convert(int, convert(bit, bcDefine12)) 是否有自定义项12, " +
                            "        convert(int, convert(bit, bcDefine13)) 是否有自定义项13, " +
                            "        convert(int, convert(bit, bcDefine14)) 是否有自定义项14, " +
                            "        convert(int, convert(bit, bcDefine15)) 是否有自定义项15, " +
                            "        convert(int, convert(bit, bcDefine16)) 是否有自定义项16, " +
                               "        cother 受控系统 " +
                            "  from    code " +
                            "  where ccode = '" + code + "' and iyear = '" + iyear + "'";
                DataTable dt = new DataTable();
                dt = DbHelper2.ExecuteTable(sql, conStr);
                if (dt.Rows.Count <= 0)
                {
                    errMsg += code+"科目档案记录不存在;";
                    return false;
                }
                else
                {
                    errMsg = "";
                    foreach (DataRow dr in dt.Rows)
                    {
                        dep_fzhs = Convert.ToInt32(dr["部门核算"].ToString());
                        person_fzhs = Convert.ToInt32(dr["人员核算"].ToString());
                        cus_fzhs = Convert.ToInt32(dr["客户核算"].ToString());
                        vendor_fzhs = Convert.ToInt32(dr["供应商核算"].ToString());
                        fitem_fzhs = Convert.ToInt32(dr["项目核算"].ToString());
                        cass_item = dr["项目大类编码"].ToString();
                        cexch_name = dr["币种"].ToString();
                        bend = Convert.ToInt32(dr["末级科目"].ToString());
                        bclose = Convert.ToInt32(dr["科目封存"].ToString());
                        //bcDefine1 = Convert.ToInt32(dr["科目封存"].ToString());

                        bcDefine1 = Convert.ToInt32(dr["是否有自定义项1"].ToString());
                        bcDefine2 = Convert.ToInt32(dr["是否有自定义项2"].ToString());
                        bcDefine3 = Convert.ToInt32(dr["是否有自定义项3"].ToString());
                        bcDefine4 = Convert.ToInt32(dr["是否有自定义项4"].ToString());
                        bcDefine5 = Convert.ToInt32(dr["是否有自定义项5"].ToString());
                        bcDefine6 = Convert.ToInt32(dr["是否有自定义项6"].ToString());
                        bcDefine7 = Convert.ToInt32(dr["是否有自定义项7"].ToString());
                        bcDefine8 = Convert.ToInt32(dr["是否有自定义项8"].ToString());
                        bcDefine9 = Convert.ToInt32(dr["是否有自定义项9"].ToString());
                        bcDefine10 = Convert.ToInt32(dr["是否有自定义项10"].ToString());
                        bcDefine11 = Convert.ToInt32(dr["是否有自定义项11"].ToString());
                        bcDefine12 = Convert.ToInt32(dr["是否有自定义项12"].ToString());
                        bcDefine13 = Convert.ToInt32(dr["是否有自定义项13"].ToString());
                        bcDefine14 = Convert.ToInt32(dr["是否有自定义项14"].ToString());
                        bcDefine15 = Convert.ToInt32(dr["是否有自定义项15"].ToString());
                        bcDefine16 = Convert.ToInt32(dr["是否有自定义项16"].ToString());
                        cother =  dr["受控系统"].ToString() ;
                    }
                }
                if (bend == 0)
                {
                    errMsg += code + "科目不是末级科目!";
                    return false;
                }
                if (bclose == 1)
                {
                    errMsg += code + "科目已封存,不能使用!";
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                errMsg += "辅助核算验证过程异常,被迫中止!" + ex.Message;
                return false;
            }
        }



        





        //部门、人员、客户、供应商、项目大类编码、项目编码是否合法）
        public bool exist_dept(string depCode, ref string errMsg)
        {
            if (string.IsNullOrWhiteSpace(depCode))
            {
                errMsg += "部门编码未输入:";
                return false;
            }

            string f1 = "select count(1) from    Department where cDepCode='" + depCode + "' and convert(int,isnull(bDepEnd,0))=1 ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "末级部门编码不存在:" + depCode;
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool exist_person(string personcode, ref string errMsg)
        {
            if (string.IsNullOrEmpty(personcode))
            {
                errMsg += "人员编码未输入:";
                return false;
            }

            string f1 = " select count(1) from    hr_hi_person where cPsn_Num='" + personcode + "' and dLeaveDate  is null ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "人员编码不存在:" + personcode;
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool exist_customer(string ccuscode, ref string errMsg)
        {
            if (string.IsNullOrEmpty(ccuscode))
            {
                errMsg += "客户编码未输入:";
                return false;
            }
            string f1 = " select count(1) from    customer where ccuscode='" + ccuscode + "' ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "客户编码不存在:" + ccuscode;
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool exist_vendor(string cVenCode, ref string errMsg)
        {
            if (string.IsNullOrEmpty(cVenCode))
            {
                errMsg += "供应商编码未输入:";
                return false;
            }
            string f1 = " select count(1) from    vendor where cVenCode='" + cVenCode + "' ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "供应商编码不存在:" + cVenCode;
                return false;
            }
            else
            {
                return true;
            }
        }

        //会计科目是否存在
        public bool exist_code(string code, int iyear,ref string errMsg)
        {
            if (string.IsNullOrEmpty(code))
            {
                errMsg += "科目编码未输入:";
                return false;
            }
            string f1 = " select count(1) from    code where ccode = '" + code + "' and iyear = '" + iyear + "'";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "科目编码不存在:" + code;
                return false;
            }
            else
            {
                return true;
            }
        }

        //项目大类编码
        public bool exist_fitem_class(string citem_class, ref string errMsg)
        {
            if (string.IsNullOrEmpty(citem_class))
            {
                errMsg += "项目大类编码未输入:";
                return false;
            }

            string f1 = " select count(1) from    fitem where citem_class='" + citem_class + "' ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "项目大类编码不存在:" + citem_class;
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cass_item">科目核算项目</param>
        /// <param name="citem_class">项目大类</param>
        /// <param name="citem_id">项目编码</param>
        /// <param name="errMsg">返回错误信息</param>
        /// <returns></returns>
        public bool exist_fitem(string code, string cass_item, string citem_class, string citem_id, ref string errMsg)
        {
            if (string.IsNullOrEmpty(code))
            {
                errMsg += "项目编码未输入:";
                return false;
            }

            if (cass_item != citem_class)
            {
                errMsg += "科目:" + code + "设置核算大类:" + cass_item + "与导入值:" + citem_class + "不符";
                return false;
            }

            string f1 = " select ctable ,cClasstable,citem_class from    fitem where citem_class='" + cass_item + "' ";
            DataTable dt = DbHelper2.ExecuteTable(f1, conStr);
            string item_class_table = "";
            string item_table = "";

            foreach (DataRow dr in dt.Rows)
            {
                item_class_table =DbHelper.GetDbString(dr["cClassTable"]);
                item_table = DbHelper.GetDbString(dr["ctable"]);
            }



            f1 = " select a.cItemCcode,a.cItemCname,b.citemcode,b.citemname " +
                 " from    " + item_class_table + " a left join " + item_table + " b on a.cItemCcode = b.citemccode";
            dt = DbHelper2.ExecuteTable(f1, conStr);
            bool flag = false;
            foreach (DataRow dr in dt.Rows)
            {
                if (citem_id == dr["citemcode"].ToString())
                {
                    flag = true;
                }
            }

            if (flag == false)
            {
                errMsg += "项目编码不存在";
            }
            return flag;
        }

        /// <summary>
        /// 判断凭证合法性
        /// </summary> 
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool pz_jc(ref string errMsg)
        {
            decimal jfje = 0;
            decimal dfje = 0;
            for (int i = 0; i < this.body.Count; i++)
            {
                Api_GL_accvouch g = this.body[i];
                //处理首行的内容
                if (i == 0)
                {
                    //读取凭证类别
                    int iSignseq = getSignSeq(g.csign);
                    if (iSignseq == -1)
                    {
                        errMsg += g.csign + "凭证类别不存在;";
                    }
                    else
                    {
                        g.isignseq = iSignseq;
                    }
                    //会计期间 
                    if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(g.dbill_date)))
                    {
                        errMsg += "凭证日期不能为空;";
                    }
                    g.iyear = DbHelper.GetDbDate(g.dbill_date).Year;
                    g.iperiod = DbHelper.GetDbDate(g.dbill_date).Month;

                    //会计期间是否结账
                    bool b2 = CheckJieZhang(g.iyear, g.iperiod, ref errMsg);
                    if (b2 == false)
                    {
                        return false;
                    }
                }
                else
                {
                    //取第一行的凭证类别
                    g.isignseq = body[0].isignseq;
                    //取第一行日期,会计期间
                    g.dbill_date = body[0].dbill_date;
                    g.iyear = body[0].iyear;
                    g.iperiod = body[0].iperiod;

                }

                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.md)))
                {
                    g.md = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.mc)))
                {
                    g.mc = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.nc_s)))
                {
                    g.nc_s = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.nd_s)))
                {
                    g.nd_s = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.nfrat)))
                {
                    g.nfrat = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.mc_f)))
                {
                    g.mc_f = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.md_f)))
                {
                    g.md_f = 0;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.idoc)))
                {
                    g.idoc = -1;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.csettle)))
                {
                    g.csettle = null;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.cn_id)))
                {
                    g.cn_id = null;
                }
                if (string.IsNullOrEmpty(DbHelper.GetDbString(g.cname)))
                {
                    g.cname = null;
                }
                if (g.md == 0 && g.mc == 0)
                {
                    errMsg += "借贷方不能同时为0!";
                }

                //外包的id，写入外部凭证id
                g.coutno_id = para.id;

                g.ibook = 0;
                g.RowGuid = System.Guid.NewGuid().ToString();
                g.bFlagOut = false;
                g.bCusSupInput = false;
                g.bItemedit = true;
                g.bDeptedit = true;
                g.bPCSedit = true;
                g.bcodeedit = true;
                g.bvalueedit = true;
                g.bvouchmoneyhold = false;
                g.bvouchAddordele = false;
                g.bvouchedit = true;
                g.bdelete = false;

                //借方金额累加，贷方金额累加
                jfje = jfje + Math.Round(DbHelper.GetDbdecimal(g.md), 2);
                dfje = dfje + Math.Round(DbHelper.GetDbdecimal(g.mc), 2);


                if (string.IsNullOrEmpty(g.cdigest))
                {
                    errMsg += "摘要必填!";
                }
                if (string.IsNullOrEmpty(g.ccode))
                {
                    errMsg += "科目必填!";
                    return false;
                }

                //币种辅助核算
                //TODO

                //科目辅助核算判断
                int b_dep_fzhs = 0;
                int b_person_fzhs = 0;
                int b_cus_fzhs = 0;
                int b_vendor_fzhs = 0;
                int b_fitem_fzhs = 0;
                string cass_item = "";
                string cexch_name = "";
                int b_bend = 0;
                int b_bclose = 0;
                int b_bcDefine1 = 0;
                int b_bcDefine2 = 0;
                int b_bcDefine3 = 0;
                int b_bcDefine4 = 0;
                int b_bcDefine5 = 0;
                int b_bcDefine6 = 0;
                int b_bcDefine7 = 0;
                int b_bcDefine8 = 0;
                int b_bcDefine9 = 0;
                int b_bcDefine10 = 0;
                int b_bcDefine11 = 0;
                int b_bcDefine12 = 0;
                int b_bcDefine13 = 0;
                int b_bcDefine14 = 0;
                int b_bcDefine15 = 0;
                int b_bcDefine16 = 0;
                string c_cother="";

                bool b3 = getFuZhuHeSuan(g.ccode, g.iyear, ref b_dep_fzhs, ref b_person_fzhs, ref b_cus_fzhs,
                              ref b_vendor_fzhs, ref b_fitem_fzhs, ref cass_item, ref cexch_name, ref b_bend, ref b_bclose, ref b_bcDefine1,
                              ref b_bcDefine2, ref b_bcDefine3, ref b_bcDefine4, ref b_bcDefine5, ref b_bcDefine6, ref b_bcDefine7,
                              ref b_bcDefine8, ref b_bcDefine9, ref b_bcDefine10, ref b_bcDefine11, ref b_bcDefine12, ref b_bcDefine13,
                              ref b_bcDefine14, ref b_bcDefine15, ref b_bcDefine16,ref c_cother, ref errMsg);

                if (!b3)
                {
                    return false;
                }


                //没有辅助核算的，内容清理干净
                string cClearErr = ClearFuZhuHeSuan(g, ref b_dep_fzhs, ref b_person_fzhs, ref b_cus_fzhs,
                                    ref b_vendor_fzhs, ref b_fitem_fzhs, ref cass_item, ref cexch_name, ref b_bend, ref b_bclose, ref b_bcDefine1,
                                    ref b_bcDefine2, ref b_bcDefine3, ref b_bcDefine4, ref b_bcDefine5, ref b_bcDefine6, ref b_bcDefine7,
                                    ref b_bcDefine8, ref b_bcDefine9, ref b_bcDefine10, ref b_bcDefine11, ref b_bcDefine12, ref b_bcDefine13,
                                    ref b_bcDefine14, ref b_bcDefine15, ref b_bcDefine16);
                if (!string.IsNullOrWhiteSpace(cClearErr))
                {
                    errMsg += cClearErr;
                    return false;
                }

                //检查有辅助核算的 ，填写的是否正确

                bool b4 = CheckFuZhuDangAn(g, b_dep_fzhs, b_person_fzhs, b_cus_fzhs, b_vendor_fzhs, b_fitem_fzhs, cass_item, b_bcDefine1, b_bcDefine2, b_bcDefine3, b_bcDefine4, b_bcDefine5, b_bcDefine6, b_bcDefine7, b_bcDefine8, b_bcDefine9, b_bcDefine10, b_bcDefine11, b_bcDefine12, b_bcDefine13, b_bcDefine14, b_bcDefine15, b_bcDefine16, ref errMsg);
                if (!b4)
                {

                    return false;

                }
            }

            if (jfje != dfje)
            {
                string errMsg_je = ";借贷金额不平衡;";
                errMsg = errMsg + errMsg_je;
              
            }
            
            if (string.IsNullOrEmpty(errMsg))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

       

        /// <summary>
        /// 判断现金流量
        /// </summary> 
        /// <param name="ccode"></param> 
        /// <returns></returns>
        private bool checkXianJinItem(string ccode)
        {
            string f1 = " select bCashItem from code where ccode='" + ccode + "' ";

            bool cCashItem_bo = DbHelper.GetDbBool(DbHelper2.ExecuteScalar(f1, conStr));
            return cCashItem_bo;
        }
        /// <summary>
        /// 判断现金流量是否正确
        /// </summary>
        /// <param name="iyear"></param>
        /// <param name="imonth"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private bool pd_xj(string cCashItem, string ccode, ref string errMsg)
        {
            string f1 = " select bCashItem from code where ccode='" + ccode + "' ";

            // int icount = Convert.ToInt32(sqlDBHelper.GetSingle(f1).ToString());
            bool cCashItem_bo = DbHelper.GetDbBool(DbHelper2.ExecuteScalar(f1, conStr));
            if (cCashItem_bo)
            {
                f1 = "select count(0) count from fitemss98 where citemcode='" + cCashItem + "'";
                int count = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
                if (count > 0)
                {
                    return true;
                }
                else
                {
                    errMsg += "输入的现金流量项目编码不正确!";
                    return false;
                }
            }
            else
            {
                errMsg += "无现金流量科目不能录入!";
                return false;
            }
        }

        /// <summary>
        /// 清除多余的辅助核算
        /// </summary>
        private string  ClearFuZhuHeSuan(Api_GL_accvouch gl, ref int dep_fzhs, ref int person_fzhs,
                                ref int cus_fzhs, ref int vendor_fzhs, ref int fitem_fzhs, ref string cass_item,
                                ref string cexch_name, ref int bend, ref int bclose,
                                ref int bcDefine1, ref int bcDefine2, ref int bcDefine3, ref int bcDefine4,
                                ref int bcDefine5, ref int bcDefine6, ref int bcDefine7, ref int bcDefine8,
                                ref int bcDefine9, ref int bcDefine10, ref int bcDefine11, ref int bcDefine12,
                                ref int bcDefine13, ref int bcDefine14, 
                                ref int bcDefine15, ref int bcDefine16)
        {           
             string errMsg = "";
            try
            {
                if (dep_fzhs == 0 && person_fzhs == 0)
                {
                    if (!string.IsNullOrEmpty(gl.cdept_id))
                    {
                        errMsg = errMsg + "科目:" + gl.ccode + "部门核算不存在，已清空;";
                    }
                    gl.cdept_id = null; 
                }
                if (person_fzhs == 0)
                {
                    gl.cperson_id = null;
                   
                }
                if (cus_fzhs == 0 )
                {
                    gl.ccus_id = null;
                   
                }
                if (vendor_fzhs == 0 )
                {
                    gl.csup_id = null;
                   
                }

                if (fitem_fzhs == 0  )
                {
                    gl.citem_id = null;
                    gl.citem_class = null; 
                }

                ////自定义项
                //if (bcDefine1 == 0 && string.IsNullOrEmpty(gl.cDefine1) == false)
                //{
                //    gl.cDefine1 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义1不存在，已清空;";
                //}
                //if (bcDefine2 == 0 && string.IsNullOrEmpty(gl.cDefine2) == false)
                //{
                //    gl.cDefine2 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义2不存在，已清空;";
                //}
                //if (bcDefine3 == 0 && string.IsNullOrEmpty(gl.cDefine3) == false)
                //{
                //    gl.cDefine3 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义3不存在，已清空;";
                //}
                //if (bcDefine4 == 0 && string.IsNullOrEmpty(DbHelper.GetDbString(gl.cDefine4)) == false)
                //{
                //    gl.cDefine4 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义4不存在，已清空;";
                //}
                //if (bcDefine5 == 0 && string.IsNullOrEmpty(DbHelper.GetDbString(gl.cDefine5)) == false)
                //{
                //    gl.cDefine5 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义5不存在，已清空;";
                //}
                //if (bcDefine6 == 0 && string.IsNullOrEmpty(DbHelper.GetDbString(gl.cDefine6)) == false)
                //{
                //    gl.cDefine6 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义6不存在，已清空;";
                //}
                //if (bcDefine7 == 0 && string.IsNullOrEmpty(DbHelper.GetDbString(gl.cDefine7)) == false)
                //{
                //    gl.cDefine7 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义7不存在，已清空;";
                //}
                //if (bcDefine8 == 0 && string.IsNullOrEmpty(gl.cDefine8) == false)
                //{
                //    gl.cDefine8 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义8不存在，已清空;";
                //}
                //if (bcDefine9 == 0 && string.IsNullOrEmpty(gl.cDefine9) == false)
                //{
                //    gl.cDefine9 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义9不存在，已清空;";
                //}
                //if (bcDefine10 == 0 && string.IsNullOrEmpty(gl.cDefine10) == false)
                //{
                //    gl.cDefine10 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义10不存在，已清空;";
                //}
                //if (bcDefine11 == 0 && string.IsNullOrEmpty(gl.cDefine11) == false)
                //{
                //    gl.cDefine11 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义11不存在，已清空;";
                //}
                //if (bcDefine12 == 0 && string.IsNullOrEmpty(gl.cDefine12) == false)
                //{
                //    gl.cDefine12 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义12不存在，已清空;";
                //}
                //if (bcDefine13 == 0 && string.IsNullOrEmpty(gl.cDefine13) == false)
                //{
                //    gl.cDefine13 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义13不存在，已清空;";
                //}
                //if (bcDefine14 == 0 && string.IsNullOrEmpty(gl.cDefine14) == false)
                //{
                //    gl.cDefine14 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义14不存在，已清空;";
                //}
                //if (bcDefine15 == 0 && string.IsNullOrEmpty(DbHelper.GetDbString(gl.cDefine15)) == false)
                //{
                //    gl.cDefine15 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义15不存在，已清空;";
                //}
                //if (bcDefine16 == 0 && string.IsNullOrEmpty(DbHelper.GetDbString(gl.cDefine16)) == false)
                //{
                //    gl.cDefine16 = null;
                //    errMsg = errMsg + "科目:" + gl.ccode + "自定义15不存在，已清空;";
                //}

                string cCashItem = DbHelper.GetDbString(gl.cCashItem);
                if (string.IsNullOrEmpty(cCashItem) == false)
                {
                    bool bo1 = checkXianJinItem(gl.ccode);
                    if (!bo1)
                    {
                        gl.cCashItem = null;
                        errMsg = errMsg + "科目:" + gl.ccode + "现金流量不存在，已清空;";
                    }
                }
                if (cexch_name.ToString().Trim() == "" && gl.cexch_name != null)
                {
                    gl.cexch_name = null;
                    errMsg = errMsg + "科目:" + gl.ccode + "币种核算不存在，已清空;";
                }
                if (gl.cexch_name == null)
                {
                    if (gl.md_f != 0)
                    {
                        gl.md_f = 0;
                        errMsg = errMsg + "科目:" + gl.ccode + "不存在外币，外币借方金额已清空;";
                    }
                    if (gl.mc_f != 0)
                    {
                        gl.mc_f =0;
                        errMsg = errMsg + "科目:" + gl.ccode + "不存在外币，外币贷方金额已清空;";

                    }

                    if (gl.nfrat != 0)
                    {
                        gl.nfrat = 0;
                        errMsg = errMsg + "科目:" + gl.ccode + "不存在外币，汇率已清空;";

                    }
                }
                return "";

            }
            catch(Exception ex)
            {
                //errMsg += "辅助核算清理错误："+ex.Message;
                return ex.Message;
            }


        }

        private bool CheckFuZhuDangAn(Api_GL_accvouch g, int b_dep_fzhs, int b_person_fzhs, int b_cus_fzhs, int b_vendor_fzhs,
          int b_fitem_fzhs, string cass_item, int b_bcDefine1, int b_bcDefine2, int b_bcDefine3, int b_bcDefine4,
          int b_bcDefine5, int b_bcDefine6, int b_bcDefine7, int b_bcDefine8, int b_bcDefine9, int b_bcDefine10,
          int b_bcDefine11, int b_bcDefine12, int b_bcDefine13, int b_bcDefine14, int b_bcDefine15, int b_bcDefine16,
          ref string errMsgall)
        {
            string errMsg = "";
            if (b_dep_fzhs == 1 && exist_dept(g.cdept_id, ref errMsg) == false)
            {
                errMsg = errMsg + "部门编码:" + g.cdept_id + "非法!";
                //return false;
            }
            if (b_person_fzhs == 1 && exist_dept(g.cdept_id, ref errMsg) == false)
            {
                errMsg = errMsg + "部门编码:" + g.cdept_id + "非法!";
                //return false;
            }


            if (b_person_fzhs == 1 && exist_person(g.cperson_id, ref errMsg) == false)
            {
                errMsg = errMsg + "人员编码:" + g.cperson_id + "非法!";
                //return false;
            }



            if (b_cus_fzhs == 1 && exist_customer(g.ccus_id, ref errMsg) == false)
            {
                errMsg = errMsg + "客户编码:" + g.ccus_id + "非法!";
                //return false;
            }


            if (b_vendor_fzhs == 1 && exist_vendor(g.csup_id, ref errMsg) == false)
            {
                errMsg = errMsg + "供应商编码:" + g.csup_id + "非法!";
                //return false;
            }

            string errMsg2 = "";

            if (b_fitem_fzhs == 1 && exist_fitem(g.ccode, cass_item, g.citem_class, g.citem_id, ref errMsg) == false)
            {
                errMsg = errMsg + "科目:" + g.ccode + ";项目核算数据" + g.citem_class + ";" + g.citem_id + "" + errMsg2;
                //return false;
            }

            //自定义项
            if ((b_bcDefine1 == 1 && string.IsNullOrEmpty(g.cDefine1) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义1数据异常";
                //return false;
            }
            if ((b_bcDefine2 == 1 && string.IsNullOrEmpty(g.cDefine2) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义2数据异常";
                //return false;
            }
            if ((b_bcDefine3 == 1 && string.IsNullOrEmpty(g.cDefine3) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义3数据异常";
                //return false;
            }
            if ((b_bcDefine4 == 1 && string.IsNullOrEmpty(DbHelper.GetDbString(g.cDefine4)) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义4数据异常";
                //return false;
            }
            if ((b_bcDefine5 == 1 && string.IsNullOrEmpty(DbHelper.GetDbString(g.cDefine5)) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义5数据异常";
                //return false;
            }
            if ((b_bcDefine6 == 1 && string.IsNullOrEmpty(DbHelper.GetDbString(g.cDefine6)) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义6数据异常";
                //return false;
            }
            if ((b_bcDefine7 == 1 && string.IsNullOrEmpty(DbHelper.GetDbString(g.cDefine7)) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义7数据异常";
                //return false;
            }
            if ((b_bcDefine8 == 1 && string.IsNullOrEmpty(g.cDefine8) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义8数据异常";
                //return false;
            }
            if ((b_bcDefine9 == 1 && string.IsNullOrEmpty(g.cDefine9) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义9数据异常";
                //return false;
            }
            if ((b_bcDefine10 == 1 && string.IsNullOrEmpty(g.cDefine10) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义10数据异常";
                //return false;
            }
            if ((b_bcDefine11 == 1 && string.IsNullOrEmpty(g.cDefine11) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义11数据异常";
                //return false;
            }
            if ((b_bcDefine12 == 1 && string.IsNullOrEmpty(g.cDefine12) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义12数据异常";
                //return false;
            }
            if ((b_bcDefine13 == 1 && string.IsNullOrEmpty(g.cDefine13) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义13数据异常";
                //return false;
            }
            if ((b_bcDefine14 == 1 && string.IsNullOrEmpty(g.cDefine14) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义14数据异常";
                //return false;
            }
            if ((b_bcDefine15 == 1 && string.IsNullOrEmpty(DbHelper.GetDbString(g.cDefine15)) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义15数据异常";
                //return false;
            }
            if ((b_bcDefine16 == 1 && string.IsNullOrEmpty(DbHelper.GetDbString(g.cDefine16)) == true))
            {
                errMsg = errMsg + "科目:" + g.ccode + "自定义15数据异常";
                //return false;
            }
            string cCashItem = DbHelper.GetDbString(g.cCashItem);
            if (string.IsNullOrEmpty(cCashItem) == false)
            {
                bool bo = pd_xj(cCashItem, g.ccode, ref errMsg);
            }

            if (string.IsNullOrEmpty(errMsg))
            {
                return true;
            }
            else
            {
                errMsgall += errMsg;
                return false;
            }

        }

        /// <summary>
        ///生成制定位数的随机码（数字）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateRandomCode(int length)
        {
            var result = new StringBuilder();
            for (var i = 0; i < length; i++)
            {
                var r = new Random(Guid.NewGuid().GetHashCode());
                result.Append(r.Next(0, 10));
            }
            return result.ToString();
        }


        public RetModel2 pz_insert()
        {
            string errMsg = "";            
            string ino_id = "";            
            string referrMsg = "";
            string yf_remark = "";
            string coutno_id = "";
             
            try
            {



                if (pz_jc(ref errMsg) == false)
                {
                    return DBService.ReErrObject("凭证检查有误:" + errMsg);
                }
                else
                {

                    int i_sql = 0;
                    int inid = 1;  //行号
                    string cpzchcode = GenerateRandomCode(20);
                    //string errMsg1 = "";

                    int i = 0;
                    string ino_idnow = "";

                    string ccode_equalmd = "";
                    string ccode_equalmc = "";
                    //外币对方科目，当前科目是外币的，才使用
                    string ccodeexch_equalmd = "";
                    string ccodeexch_equalmc = "";
                    //生成对方科目
                    foreach (Api_GL_accvouch g in body)
                    {
                        if (g.md == 0)
                        {
                            ccode_equalmd += g.ccode + ",";
                       

                            if (string.IsNullOrEmpty(g.cexch_name))
                            {
                                ccodeexch_equalmd += g.ccode + "|" + benbi + ",";
                            }
                            else
                            {
                                ccodeexch_equalmd += g.ccode + "|"+ g.cexch_name + ",";
                            }
                           

                        }
                        if (g.mc == 0)
                        {
                            ccode_equalmc += g.ccode + ",";
                            if (string.IsNullOrEmpty(g.cexch_name))
                            {
                                ccodeexch_equalmc += g.ccode + "|" + benbi + ",";
                            }
                            else
                            {
                                ccodeexch_equalmc += g.ccode + "|" + g.cexch_name + ",";
                            }
                        }
                    }
                    foreach (Api_GL_accvouch g in body)
                    {
                        if (i == 0)
                        {
                            //获取凭证编号
                            ino_idnow = get_ino_id(g.iyear, g.iperiod, g.csign);
                            coutno_id = get_coutno_id();
                            if (int.Parse(ino_idnow) > 32767)
                            {
                               string  messBox = "此凭证类别本月数量已经达到最大值：" + g.csign + ino_idnow;
                                referrMsg = "生成有误:" + messBox;
                                throw new Exception(referrMsg);

                            }
                            i++;
                        }
                        if (g.mc == 0 && ccode_equalmd.Length > 0)
                        {
                            g.ccode_equal = ccode_equalmd.Substring(0, ccode_equalmd.Length - 1);
                           
                            string ccode_equal = g.ccode_equal;
                            //g.ccode_equal = ccode_equalmd.Substring(0, ccode_equalmd.Length - 1);
                            //长度大于50的，只取前面50以内的
                            if (g.ccode_equal != null && g.ccode_equal.Length > 50)
                            {
                                string[] arrlist = g.ccode_equal.Split(',');
                                for (int q = 0; q < arrlist.Length; q++)
                                {
                                    if (q == 0)
                                    {
                                        ccode_equal = arrlist[q];
                                    }
                                    else if (ccode_equal.Length + arrlist[q].Length + 1 < 50)
                                    {
                                        ccode_equal += "," + arrlist[q];
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }

                            g.ccode_equal = ccode_equal;

                            //如果当前行是外币的，使用外币对方科目
                            if (!string.IsNullOrEmpty(g.cexch_name))
                            {
                                string ccodeexch_equal = ccodeexch_equalmd.Substring(0, ccodeexch_equalmd.Length - 1);
                                //g.ccode_equal = ccode_equalmd.Substring(0, ccode_equalmd.Length - 1);
                                //长度大于50的，只取前面50以内的
                                if (g.ccodeexch_equal != null && g.ccodeexch_equal.Length > 50)
                                {
                                    string[] arrlist = g.ccodeexch_equal.Split(',');
                                    for (int q = 0; q < arrlist.Length; q++)
                                    {
                                        if (q == 0)
                                        {
                                            ccodeexch_equal = arrlist[q];
                                        }
                                        else if (ccodeexch_equal.Length + arrlist[q].Length + 1 < 50)
                                        {
                                            ccodeexch_equal += "," + arrlist[q];
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                g.ccodeexch_equal = ccodeexch_equal;
                            }
                            else
                            {
                                g.ccodeexch_equal = ccode_equal;
                            }

                        }
                        if (g.md == 0 && ccode_equalmc.Length > 0)
                        {
                            g.ccode_equal = ccode_equalmc.Substring(0, ccode_equalmc.Length - 1);

                            string ccode_equal = g.ccode_equal;
                            //g.ccode_equal = ccode_equalmd.Substring(0, ccode_equalmd.Length - 1);
                            if (g.ccode_equal != null && g.ccode_equal.Length > 50)
                            {
                                string[] arrlist = g.ccode_equal.Split(',');
                                for (int q = 0; q < arrlist.Length; q++)
                                {
                                    if (q == 0)
                                    {
                                        ccode_equal = arrlist[q];
                                    }
                                    else if (ccode_equal.Length + arrlist[q].Length + 1 < 50)
                                    {
                                        ccode_equal += "," + arrlist[q];
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            g.ccode_equal = ccode_equal;

                            //如果当前行是外币的，使用外币对方科目
                            if (!string.IsNullOrEmpty(g.cexch_name))
                            {
                                string ccodeexch_equal = ccodeexch_equalmc.Substring(0, ccodeexch_equalmc.Length - 1);
                                //g.ccode_equal = ccode_equalmd.Substring(0, ccode_equalmd.Length - 1);
                                //长度大于50的，只取前面50以内的
                                if (g.ccodeexch_equal != null && g.ccodeexch_equal.Length > 50)
                                {
                                    string[] arrlist = g.ccodeexch_equal.Split(',');
                                    for (int q = 0; q < arrlist.Length; q++)
                                    {
                                        if (q == 0)
                                        {
                                            ccodeexch_equal = arrlist[q];
                                        }
                                        else if (ccodeexch_equal.Length + arrlist[q].Length + 1 < 50)
                                        {
                                            ccodeexch_equal += "," + arrlist[q];
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                g.ccodeexch_equal = ccodeexch_equal;
                            }
                            else
                            {
                                g.ccodeexch_equal = ccode_equal;
                            }
                        }
                        g.coutno_id = coutno_id;
                        g.ino_id = DbHelper.GetDbInt(ino_idnow);
                        g.inid = DbHelper.GetDbInt(inid.ToString());
                        inid++;
                        //g.cpzchcode = cpzchcode;

                        ino_id = g.csign + g.ino_id;
                        yf_remark = g.iyear + "-" + g.iperiod + "-" + g.csign + "-" + ino_idnow;
                    }

                    RetModel2 ret = Add(ref yf_remark);
                    
                    return ret;



                }
            }
            catch (Exception ees)
            {

                referrMsg = "生成有误:" + ees.ToString();
                return DBService.ReErrObject(referrMsg);
            }
        
        }

        // 插入数据库
        public RetModel2 Add(ref string yf_remark)
        {

            try
            {
                //转换成插入的数据实体
                List<GL_accvouch> entity = new List<GL_accvouch>();
                foreach (var item in body)
                {
                    entity.Add(item);
                }

                var db1 = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                });
                String cpz = JsonConvert.SerializeObject(entity);
                ExLog.WriteTxt("PZ", cpz);
                try
                {
                    db1.Ado.BeginTran();
                    int ire = db1.Insertable<GL_accvouch>(entity).ExecuteCommand();
                    if (ire < 2)
                    {
                        db1.Ado.RollbackTran();
                        throw new Exception("凭证数据小于2行");
                    }
                    db1.Ado.CommitTran();
                    return DBService.ReOKObject(yf_remark);
                }
                catch (Exception ex)
                {
                    db1.Ado.RollbackTran();
                    throw ex;
                }
 
              
              
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject($"操作失败: {ex.Message}");
            }

        }

    }
}
